<?php

class WxSimilar extends AppModel {

    var $name = 'WxSimilar';
    
    public function beforeSave($options = array())
    {
    	parent::beforeSave($options);
    	
    	if($this->data['WxSimilar']['words']) {
    	    if( is_array($this->data['WxSimilar']['words']) ){
    	        $words = $this->data['WxSimilar']['words'];
    	    }
    	    else{
    	        $words = explode("\r\n",$this->data['WxSimilar']['words']);
    	    }
    	    
    	    foreach($words as &$w){
    	        $w = trim($w);
    	    }
    	    $this->data['WxSimilar']['words'] = ','.implode(',',$words).',';
    	}
    	return true;
    }

    /**
     * 获取词的同义词
     * @param $word 搜索词
     * @param $wd_id 编号数字，或者编号数组
     * @return string
     */
    public function getSimilarWord($word,$wd_id) {
        $word = trim($word);
        $item = $this->find('first',array(
            'conditions' => array(
               'or' => array(
                   'words like' => "%,$word,%",
                   'name' => $word,
               ),
               'wx_id' => $wd_id,
               'status' => 1,
            ),
        ));
        if(!empty($item)){
            return $item['WxSimilar']['name'];
        }
        else{
            return $word;
        }
    }
    
    public function afterFind($results, $primary = false) {
    	foreach($results as &$msg) {
    	    $words = explode(',',$msg['WxSimilar']['words']);    	    
    		$msg['WxSimilar']['words'] = trim(implode("\r\n",$words));
    	}
    	return $results;
    }
}
?>